package com.xxl.job.admin.service.impl;

import com.xxl.job.admin.core.model.CronJob;
import com.xxl.job.admin.core.model.Server;
import com.xxl.job.admin.dao.CronJobDao;
import com.xxl.job.admin.dao.ServerDao;
import com.xxl.job.admin.dto.CronJobDetailsDto;
import com.xxl.job.admin.dto.CronJobRequest;
import com.xxl.job.admin.dto.JobResultDTO;
import com.xxl.job.admin.dto.Page;
import com.xxl.job.admin.service.CronJobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CronJobServiceImpl implements CronJobService {

    @Autowired
    private CronJobDao cronJobDao;

    @Autowired
    private ServerDao serverDao  ;

    @Override
    public Page<CronJobDetailsDto> getCronJobDetails(String ip, String owner, String systemName,String serverUser,String command,int page, int size) {
        int offset = (page - 1) * size;
        List<CronJobDetailsDto> cronJobs = cronJobDao.findCronJobDetails(ip, owner, systemName,serverUser,command, offset, size);
        // 遍历结果并确保所有字段有值
        for (CronJobDetailsDto job : cronJobs) {
            job.setId(job.getId());
            job.setIp(job.getIp() != null ? job.getIp() : "");
            job.setOwner(job.getOwner() != null ? job.getOwner() : "");
            job.setSystemName(job.getSystemName() != null ? job.getSystemName() : "");
            job.setSchedule(job.getSchedule() != null ? job.getSchedule() : "");
            job.setCommand(job.getCommand() != null ? job.getCommand() : "");
            job.setServerUser(job.getServerUser() != null ? job.getServerUser() : "");
            job.setStatus(job.getStatus() != null ? job.getStatus() : 0);
            job.setUpdatedAt(job.getUpdatedAt() != null ? job.getUpdatedAt() : null);
        }
        int total = cronJobDao.countCronJobs(ip, owner, systemName,serverUser,command);
        return new Page<>(cronJobs, total, page, size);  // 自定义 Page 对象封装分页信息
    }

    @Override
    public Integer findExecutorIdByJobHandler(String jobHandler) {
        Integer result = cronJobDao.findExecutorIdByJobHandler(jobHandler);
        if (result == null) {
            return null;
        }
        return result;
    }

    @Override
    public void updateCronJobStatus(long jobId, int status, String schedule) {
        System.out.println("Executing SQL: UPDATE cron_jobs SET status=" + status + ", schedule=" + schedule + ", updated_at=NOW() WHERE id=" + jobId);
        cronJobDao.updateCronJobStatus(jobId, status,schedule);
    }

    @Override
    public CronJobDetailsDto findById(long jobId) {
        return cronJobDao.findById(jobId);
    }

    @Override
    public void updateCronJob(long jobId, String schedule, String command, String owner, String systemName,Integer newStatus) {
        cronJobDao.updateCronJob(jobId, schedule, command, owner, systemName,newStatus);
    }

    @Override
    public void addCronJob(CronJobRequest cronJobRequest) {
        // 根据 IP 检查服务器是否存在
        Server server = serverDao.findByIp(cronJobRequest.getIp());

        if (server == null) {
            // 如果服务器不存在，则插入新的服务器记录
            server = new Server();
            server.setIp(cronJobRequest.getIp());
            server.setOwner(cronJobRequest.getOwner());
            server.setSystemName(cronJobRequest.getSystemName());
            serverDao.insertServer(server);

            // 插入后获得自动生成的 server_id
            int serverId = server.getId();
            server.setId(serverId);
        }

        // 检查调度时间是否以 # 开头，来设置状态
        int status = cronJobRequest.getSchedule().startsWith("#") ? 0 : 1;

        // 创建定时任务对象
        CronJob cronJob = new CronJob();
        cronJob.setServerId(server.getId());
        cronJob.setSchedule(cronJobRequest.getSchedule());
        cronJob.setCommand(cronJobRequest.getCommand());
        cronJob.setServerUser(cronJobRequest.getServerUser());
        cronJob.setStatus(status);

        // 插入定时任务
        cronJobDao.insertCronJob(cronJob);
    }

    @Override
    public Integer findJobIdByAddWork(String ip, String schedule, String command) {
        Integer result = cronJobDao.findJobIdByAddWork(ip,schedule,command);
        if (result == null) {
            return null;
        }
        return result;
    }




}
